#!/usr/bin/env	python
#coding:utf-8

import MySQLdb
from aes import *

class conn_mysql:

    def __init__(self):
        self.conn = MySQLdb.connect(host='xxx',user='xxx',passwd='xxx',charset='utf8')
        self.cur = self.conn.cursor()
        self.encrypt_pass = aes_crypto()

    def update_pass(self,user,newpass):
        pwd = base64.encodestring(self.encrypt_pass.encrypt_aes(passwd)).split()
        sql = "update oms.auth_ldap set pwd='%s' where user='%s'"
        self.cur.execute(sql %(pwd,user))
        self.conn.commit()

    def del_user(self,uid):
        sql = "delete from oms.auth_ldap where user='%s'"
        self.cur.execute(sql %uid)
        self.conn.commit()

    def add_user(self,user,passwd,uid,gid,dept,mail=None):
        sql = "insert into oms.auth_ldap(user,pwd,uid,gid,dept,mail) values('%s','%s','%s','%s','%s','%s')"
        pwd = base64.encodestring(self.encrypt_pass.encrypt_aes(passwd)).split()[0]
        self.cur.execute(sql %(user,pwd,uid,gid,dept,mail))
        self.conn.commit()

    def s_uid(self):
        sql = "select uid from oms.auth_ldap order by uid desc limit 1"
        self.cur.execute(sql)
        u = self.cur.fetchall()[0][0]
        return u

    def s_gid(self,dept=None,user=None):
        if user:
            sql = "select gid from oms.auth_ldap where user='%s'"
            self.cur.execute(sql %user)
            g = self.cur.fetchall()
            return g
        if dept:
            sql = "select gid from oms.auth_ldap where dept='%s' limit 1"
            self.cur.execute(sql %dept)
            g = self.cur.fetchall()[0][0]
            return g
        sql = "select gid from oms.auth_ldap order by gid desc limit 1"
        self.cur.execute(sql)
        g = self.cur.fetchall()[0][0]
        return g

    def r_pas(self):
       import random
       import string
       seed = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+=-"
       sa = []
       for i in range(6):
           sa.append(random.choice(seed))
       passwd = ''.join(sa)
       return passwd

    def r_ip(self,user):
        sql = "select dept from oms.auth_ldap where user='%s'"
        self.cur.execute(sql %user)
        dept = self.cur.fetchall()[0][0]
        sql1 = "select n_ip from webserver.asset_hosts where bm='%s'"
        self.cur.execute(sql1 %dept)
        ip = []
        for x in self.cur.fetchall():
            ip.append(x[0])
        return ip

    def s_pass(self,user):
        sql = "select pwd from oms.auth_ldap where user='%s'"
        self.cur.execute(sql %user)
        pwd = self.cur.fetchall()[0][0]
        p = self.encrypt_pass.decrypt_aes(base64.decodestring(pwd))
        return p

if __name__ == '__main__':
    c = conn_mysql()
    print c.s_pass('zhangjun')
